﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Script.Serialization;

using SF.Export;
using SF.Utilities;

namespace SF.WebClient.Controllers
{
    public class PublicController : Controller
    {
        public ViewResult ExampleIndex(string module, string extension)
        {
            ViewBag.Module = module;
            ViewBag.Extension = extension;

            return View();
        }

        public ViewResult QAIndex()
        {
            return View();
        }

        /// <summary>
        /// datagrid导出数据
        /// </summary>
        /// <param name="data">datagrid的data数据的json格式，将被反序列化成 DataTable </param>
        /// <param name="columns">datagrid的columns数据的json格式，将被反序列化成 DataTable[]，其中列是固定的“field、title、rowspan、colspan” </param>
        /// <param name="fileName">excel文件名</param>
        /// <param name="url">查询远程数据的地址，若该参数存在并获取到数据，则将忽略<see cref="data"/>参数的值</param>
        /// <returns></returns>
        public FileResult ExportToExcelFromDatagrid([ModelBinder(typeof(DatagridRowsJsonBinder))]System.Data.DataTable data, [ModelBinder(typeof(DatagridColumnsJsonBinder))]System.Data.DataTable[] columns, string fileName, string url)
        {
            if (columns.Length == 0) { throw new Exception("列不存在，无法导出！"); }
            if (!string.IsNullOrWhiteSpace(url))
            {
                string hostUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port;
                using (var hc = new HttpClient())
                {
                    try
                    {
                        var requestJson = (new JavaScriptSerializer()).Serialize(new { rows = 0 });
                        HttpContent httpContent = new StringContent(requestJson);
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        var responseJson = hc.PostAsync(hostUrl + url, httpContent).Result.Content.ReadAsStringAsync().Result;
                        var obj = SF.Utilities.Serialization.DeserializeJsToObject<dynamic>(responseJson);
                        //处理数据行中的Object和Array类型的数据，若不处理将无法转换成DataTable
                        foreach (dynamic item in obj.rows)
                        {
                            var props = ((Newtonsoft.Json.Linq.JObject)item).Properties();
                            foreach (var p in props)
                            {
                                var value = p.Value;
                                if (value.Type == Newtonsoft.Json.Linq.JTokenType.Array) { p.Value = "[Array]"; }
                                else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Object) { p.Value = "[Object]"; }
                            }
                        }
                        string json = SF.Utilities.Serialization.ToJson(obj.rows);
                        if (json.StartsWith("[") && json.EndsWith("]"))
                        {
                            if (json.StartsWith("[[") && json.EndsWith("]]"))
                            {
                                //处理columns
                            }
                            else
                            {
                                data = SF.Utilities.Serialization.DeserializeJsToDataTable(json);
                            }
                        }
                    }
                    catch { }
                }
            }

            IEnumerable<MergerCellParamModel> rules = null;
            DataTable dt = EasyuiDatagridExport.ParseColumnsAndRows(columns, data, out rules);

            var content = NPOIExport.ExportToExcel(dt, false, rules, true, true, false);

            if (string.IsNullOrWhiteSpace(fileName)) { fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "导出"; }
            return File(content, "application/ms-excel", Url.Encode(fileName + ".xls"));
        }
    }
}